//
//  ONRealTimeViewController.m
//  Volatix
//
//  Created by Anh Tran on 6/2/14.
//  Copyright (c) 2014 Familly. All rights reserved.
//


#import "ONRealTimeViewController.h"

@interface ONRealTimeViewController () <SWTableViewCellDelegate,ONTabbarViewControllerDelegate>
@property (nonatomic) BOOL useCustomCells;
@property (nonatomic, weak) UIRefreshControl *refreshControl;


@end

@implementation ONRealTimeViewController


- (void)viewDidLoad
{
    [super viewDidLoad];
     NSLog(@"%s",__FUNCTION__);
    self.dataArray = [[NSMutableArray alloc]init];
    if(_iData==nil)
    {
        _iData= [[NSMutableArray alloc] init];
        _iData = [NSMutableArray arrayWithArray:[APP_DELEGATE getingDataSymbleForTypeScreen:0]];
        [self customizeDataSaving:false];
        
    }
    else
    {
        //// get all loadZone / powerPoint to iData
        [self.dataArray removeAllObjects];
        [_iData removeAllObjects];
        if(_level==(LEVEL_ISO+1))
        {
            NSMutableDictionary *params = [NSMutableDictionary dictionary];
            [params setObject:[NSNumber numberWithInt:0]  forKey:@"PageIndex"];
            [params setObject:[NSNumber numberWithInt:100] forKey:@"pageSize"];
            [params setObject:self.ISO forKey:@"ISO"];
            [[WebserviceManager sharedInstance] operationWithType:ENUM_API_REQUEST_LIST_LOADZONE andPostMethodKind:enumAPIRequestMethod_GET andParams:params andString:nil inView:self.view completeBlock:^(id responseObject) {
                self.dataArray = [NSMutableArray array];
                for (id item in responseObject) {
                    ONISOObjects *isoObject = [ONISOObjects modelObjectWithDictionary:item];
                    isoObject.type=LEVEL_LOADZONE;
                    isoObject.iso=self.ISO;
                    isoObject.loadZone=nil;
                    // NSLog(@"***** %@",isoObject.name);
                    [_iData addObject:isoObject];
                    
                }
                [self customizeDataSaving:false];
            } failureBlock:^(NSError *error) {
                ///
            }];

        }
        else if(_level==(LEVEL_LOADZONE+1))
        {
            NSMutableDictionary *params = [NSMutableDictionary dictionary];
            [params setObject:[NSNumber numberWithInt:0]  forKey:@"PageIndex"];
            [params setObject:[NSNumber numberWithInt:100] forKey:@"pageSize"];
            [params setObject:self.ISO forKey:@"ISO"];
            [params setObject:self.LOADZONE forKey:@"LOADZONE"];
            [[WebserviceManager sharedInstance] operationWithType:ENUM_API_REQUEST_LIST_POWERPOINT andPostMethodKind:enumAPIRequestMethod_GET andParams:params andString:nil inView:self.view completeBlock:^(id responseObject) {
                ///
                self.dataArray = [NSMutableArray array];
                for (id item in responseObject) {
                    ONISOObjects *isoObject = [ONISOObjects modelObjectWithDictionary:item];
                    isoObject.iso=self.ISO;
                    isoObject.type=LEVEL_POWERPOINT;
                    isoObject.loadZone=self.LOADZONE;
                    [_iData addObject:isoObject];
                    
                }
                [self customizeDataSaving:false];
               
            } failureBlock:^(NSError *error) {
                ///
            }];
            
            
        }
        
        
    }
    self.isShowingSelectColumnView = NO;
    [self initRootColumn];
    [self startPullDownRefresh];
    _postNotifiGetData=true;
    // Do any additional setup after loading the view.
    [self requestUpdateData];
    [NSTimer scheduledTimerWithTimeInterval:TIME_CHECK
                                     target:self
                                   selector:@selector(requestUpdateData)
                                   userInfo:nil
                                    repeats:YES];
    
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clickDone) name:SAVING_DATA_REAL_TIME object:nil];
}


#pragma mark - INIT COLUMN DYNAMIC
-(void)initRootColumn
{
    // kNumberOfColumnOnRealTime basic 3 column
    ONTabbarViewController *tabbar =(ONTabbarViewController*)self.tabBarController;
    if(self.columnArray==nil){
        self.columnArray = [[NSMutableArray alloc]init];
    }
    for (int i=0; i<4; i++)
    {
        
        ONColumnTitleObject *column = [[ONColumnTitleObject alloc]init];
        
        if (i==0) {
            column.name = @"Point";
            column.allowToSelect = NO;
            column.mainColumn=1;
        } else if (i==1 || i==2) {
            NSMutableArray *arrayColumn=[APP_DELEGATE getingCurrentColumnNameRealTime];
            if(arrayColumn==nil)
            {
                
                column.name = [NSString stringWithFormat:@"%@",(i==1)?@"High (H)":@"Low (H)"];//column.name = [NSString stringWithFormat:@"%@▾",(i==1)?@"Hourly High":@"Hourly Low"];
                column.allowToSelect = YES;
                NSMutableArray *tempArray = [[NSMutableArray alloc]initWithObjects:@"Hourly High",@"Hourly Low", nil];
                [APP_DELEGATE savingCurrentColumnNameRealTime:tempArray];
                self.currentMenuIndex = 0;
                tabbar.ChoiceTypeDataFilter=HOURLY;
               
            }
            else
            {
                
                NSString *item=[arrayColumn objectAtIndex:0];
               // NSString *item =[columnItem objectAtIndex:0];
                NSString *strHigh=@"";
                NSString *strLow=@"";
                if([item isEqualToString:@"Hourly High"])
                {
                    strHigh =@"Hight (H)";
                    strLow =@"Low (H)";
                }
                else if([item isEqualToString:@"Daily High"])
                {
                    strHigh =@"Hight (D)";
                    strLow =@"Low (D)";
                }
                else if([item isEqualToString:@"Weakly High"])
                {
                    strHigh =@"Hight (W)";
                    strLow =@"Low (W)";
                }
                else
                {
                    strHigh =@"Hight (M)";
                    strLow =@"Low (M)";
                    ///Monthly High
                }

                
                column.name = [NSString stringWithFormat:@"%@",(i==1)?strHigh:strLow];
                //column.name = [NSString stringWithFormat:@"%@▾",(i==1)?[arrayColumn objectAtIndex:0]:[arrayColumn objectAtIndex:1]];
                column.allowToSelect = YES;
                
                if ([item isEqualToString:@"Hourly High"]) {
                    self.currentMenuIndex = 0;
                    tabbar.ChoiceTypeDataFilter=HOURLY;
                }
                else if([item isEqualToString:@"Daily High"])
                {
                    self.currentMenuIndex = 1;
                    tabbar.ChoiceTypeDataFilter=DAILY;
                }
                else if([item isEqualToString:@"Weakly High"])
                {
                    self.currentMenuIndex = 2;
                    tabbar.ChoiceTypeDataFilter=WEAKLY;
                }
                else if([item isEqualToString:@"Monthly High"])
                {
                    self.currentMenuIndex = 3;
                    tabbar.ChoiceTypeDataFilter=MONTHLY;
                }
                
            }
             column.mainColumn=1;
        }
        else if(i==3)
        {
            column.name = [NSString stringWithFormat:@"Current"];
            column.allowToSelect = NO;
            column.mainColumn=1;
        }
        [self.columnArray addObject:column];
        [self.columnArray sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
            ONColumnTitleObject *p1 = (ONColumnTitleObject*)obj1;
            ONColumnTitleObject *p2 = (ONColumnTitleObject*)obj2;
            
            if (p1.mainColumn < p2.mainColumn) {
                return (NSComparisonResult)NSOrderedDescending;
            }
            
            if (p1.mainColumn > p2.mainColumn) {
                return (NSComparisonResult)NSOrderedAscending;
            }
            return (NSComparisonResult)NSOrderedSame;
            
            
        }];
    }
    
    // menu hardcode data
    self.columnMenuArray = [[NSMutableArray alloc]init];
    NSMutableArray *tempArray_1 = [[NSMutableArray alloc]initWithObjects:@"Hourly High",@"Hourly Low", nil];
    NSMutableArray *tempArray_2 = [[NSMutableArray alloc]initWithObjects:@"Daily High",@"Daily Low", nil];
    NSMutableArray *tempArray_3 = [[NSMutableArray alloc]initWithObjects:@"Weakly High",@"Weakly Low", nil];
    NSMutableArray *tempArray_4 = [[NSMutableArray alloc]initWithObjects:@"Monthly High",@"Monthly Low", nil];
    [_columnMenuArray addObject:tempArray_1];
    [_columnMenuArray addObject:tempArray_2];
    [_columnMenuArray addObject:tempArray_3];
    [_columnMenuArray addObject:tempArray_4];
}






# pragma mark - TABBAR DELEGATE

-(void)ONLeftItemselected:(id)sender
{
    NSLog(@"%s",__FUNCTION__);
    switch (_level) {
        case LEVEL_ISO:
        {
            UINavigationController *vc =(UINavigationController *)[self.storyboard instantiateViewControllerWithIdentifier:@"ONAddSymbolViewController"];
            [self.navigationController presentViewController:vc animated:true completion:^{
                ///
            }];
        }
            break;
        case LEVEL_LOADZONE:
            //
            
            [self.navigationController popViewControllerAnimated:true];
            break;
        case LEVEL_POWERPOINT:
            //
            [self.navigationController popViewControllerAnimated:true];
            break;
            
        default:
            break;
    }
    
    
}
-(void)ONRightItemselected:(id)sender
{
    NSLog(@"%s",__FUNCTION__);
    
    UINavigationController *vc =(UINavigationController *)[self.storyboard instantiateViewControllerWithIdentifier:@"ONSettingsViewController"];
    [self.navigationController presentViewController:vc animated:true completion:^{
        ///
    }];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
     [Utils SetISO:self.ISO andLoadZone:self.LOADZONE];
    ONTabbarViewController *tabbar =(ONTabbarViewController*)self.tabBarController;
    [Utils setCurrentType:(int)_level];
    [tabbar.ButtonLeft setImage:[UIImage imageNamed:(_level==LEVEL_ISO)?@"btn_add.png":@"arrow_left.png"] forState:UIControlStateNormal];
    [self initDelegateTabbar:true];
    _postNotifiGetData=true;
    self.tabBarController.title = (_level==(LEVEL_ISO+1))?[NSString stringWithFormat:@"LOADZONE-%@",self.ISO]:(_level==(LEVEL_LOADZONE+1))?[NSString stringWithFormat:@"POWERPOINT-%@",self.LOADZONE]:@"REAL TIME";
    /// get filter data
    self.filerData =[NSMutableArray arrayWithArray:[APP_DELEGATE getingFilterBySymble:[self getRequestFiter:0]]];//[APP_DELEGATE getingFilterTimerForTypeScreen:0]];//getingFilterTimerForRealTime:YES]];
    [self.tableView reloadData];
    
}
-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    _postNotifiGetData=false;
    
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [Utils setTypeScreen:0];
    [Utils setMainScreen:(self.level==LEVEL_ISO)?true:false];
    if (animated) {
        
        [self updateUIForViewWithColumn:kNumberOfColumnOnRealTime];
    }
    
    

}
/**
 * Checking has child
 */
-(BOOL)checkingHasChildByName:(NSString *)name
{
    for (int index=0; index<[_iData count]; index++) {
        ONISOObjects *oNISOObject = [_iData objectAtIndex:index];
       
//       if(oNISOObject.iso!=nil&&[oNISOObject.iso isEqualToString:name]&&_level==LEVEL_ISO)
//       {
//           return true;
//       }
//        
//        if(oNISOObject.loadZone!=nil&&[oNISOObject.loadZone isEqualToString:name]&&_level==LEVEL_LOADZONE)
//        {
//            return true;
//        }
//        
        if([oNISOObject.name isEqualToString:name]&&oNISOObject.hasChild==true)
        {
            return true;
        }
        
        
    }
    return false;
}


-(void)customizeDataSaving:(BOOL)value
{
    if(value&&(_level==LEVEL_ISO))
    {
        [APP_DELEGATE savingDataSymble:_iData andTypeScreen:0];//savingDataSymble:_iData andRealtime:true];
    }
    self.dataArray =[NSMutableArray arrayWithArray:_iData];
    /// sort data
    [self.dataArray sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        ONISOObjects *p1 = (ONISOObjects*)obj1;
        ONISOObjects *p2 = (ONISOObjects*)obj2;
        
        if (p1.type > p2.type) {
            return (NSComparisonResult)NSOrderedDescending;
        }
        
        if (p1.type < p2.type) {
            return (NSComparisonResult)NSOrderedAscending;
        }
        return (NSComparisonResult)NSOrderedSame;
        
        
    }];
    
    
    [self.tableView reloadData];

    
}
-(NSString*)getStringDatafollowlevelBy:(ONISOObjects *)_obj
{
    return  (_level==LEVEL_ISO)?_obj.iso:(_level==LEVEL_LOADZONE)?_obj.loadZone:@"ANTListLevel3";
}
-(BOOL)checkExit:(NSString *)name andArray:(NSMutableArray *)array
{
    for (int index=0; index<[array count]; index++) {
        ONISOObjects *strName =[array objectAtIndex:index];
        if([strName.name isEqualToString:[NSString stringWithFormat:@"%@",name]])
        {
            return true;
        }
        
    }
 
    return false;
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    // Get current controller
    if ([self.navigationController.visibleViewController isKindOfClass:[ONAddSymbolViewController class]]) {
        
        ONAddSymbolViewController *controller = (ONAddSymbolViewController *)self.navigationController.visibleViewController;
        controller.addSymbolItemsArray = self.dataArray;
        controller.typeScreen=0;
        // current data
        controller.currentRealTimeData = [[NSMutableArray alloc]init];
        for ( ONISOObjects *oNISOObject in self.dataArray) {
            [controller.currentRealTimeData addObject:oNISOObject];
        }
        
    } else if ([self.navigationController.visibleViewController isKindOfClass:[ONSettingsViewController class]]) {
        
         ONSettingsViewController *controller = (ONSettingsViewController *)self.navigationController.visibleViewController;
        controller.dataArray=self.dataArray;
       
        
    }
    
    // Set Image
}

#pragma mark - Private Methods

- (NSArray *)rightButtons
{
    NSMutableArray *rightUtilityButtons = [NSMutableArray new];
    
    [rightUtilityButtons sw_addUtilityButtonWithColor:
     [UIColor colorWithRed:99.0/255.0 green:187.0/255.0 blue:3.0/255.0 alpha:1.0]icon:[UIImage imageNamed:@"btn_swift_alert"]];
    [rightUtilityButtons sw_addUtilityButtonWithColor:
     [UIColor colorWithRed:99.0/255.0 green:187.0/255.0 blue:3.0/255.0 alpha:1.0]
                                                icon:[UIImage imageNamed:@"btn_swift_remove"]];
    
    return rightUtilityButtons;
}

- (void)updateUIForViewWithColumn:(int) _nColumn{
    
    CGRect tableViewFrame = self.tableView.frame;
    CGRect pullDownViewFrame = self._refreshHeaderView.frame;
    
    // Update Tableview frame
    tableViewFrame.size.width = kWidthColumn * (_nColumn + 1);
    self.tableView.frame = tableViewFrame;
    
    // Update scrollView content size
    CGSize contentSize = self.tableView.contentSize;
    contentSize.height = 0;

    self.scrollView.contentSize =  contentSize;
    
    self._refreshHeaderView.frame = pullDownViewFrame;
}
-(BOOL)isInVisibleArray:(ONISOObjects *)item
{
    for (int index=0; index<[self.filerData count]; index++) {
        ONISOObjects *_is=[self.filerData objectAtIndex:index];
        if([item.name isEqualToString:_is.name])
        {
            return true;
        }
    }
    
    return false;
}
#pragma mark - Action Methods

- (void)selectColumnButtonPressed:(id)sender {
    self.isShowingSelectColumnView = YES;
    [self.tableView reloadData];
}

#pragma mark - UIScrollViewDelegate

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    if ([scrollView.panGestureRecognizer translationInView:scrollView.superview].x > 0) {
        // handle dragging to the right
    } else {
        // handle dragging to the right
    }
}

#pragma mark - UITableViewDataSource Methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    
    NSInteger numberOfCell = 0;
    if (self.isShowingSelectColumnView) {
        numberOfCell = [self.columnMenuArray count]+[self.dataArray count];
    } else {
        numberOfCell = [self.dataArray count];
    }
    return numberOfCell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return kHeightSection;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if(self.isShowingSelectColumnView)
    {
        return 30;
    }

   // if(indexPath.row>=[self.dataArray count]){return 30;}
   // NSLog(@"--------- %d",[self isInVisibleArray:[self.dataArray objectAtIndex:indexPath.row]])?0:30);
    return ([self isInVisibleArray:[self.dataArray objectAtIndex:indexPath.row]])?0:30;
    
}



- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    UIView *sectionView = [[UIView alloc]init];
    sectionView.backgroundColor = [UIColor clearColor];
    
    CGFloat currentX = 0;
    
    for (int i=0; i<[self.columnArray count]; i++) {
        ONRealTimeSectionView *view = [[ONRealTimeSectionView alloc]initWithFrame:CGRectMake(0, 0, kWidthColumn, kHeightSection)];
     
        ONColumnTitleObject *column = [self.columnArray objectAtIndex:i];
        view.titleLabel.text = column.name;
        
        if (column.allowToSelect) {
            view.selectColumnButton.userInteractionEnabled = YES;
        } else {
            view.selectColumnButton.userInteractionEnabled = NO;
        }
        
        [view.selectColumnButton addTarget:self action:@selector(selectColumnButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
 
        currentX = i*kWidthColumn;
        
        view.frame = CGRectMake(currentX, 0, kWidthColumn, kHeightSection);
        sectionView.frame = CGRectMake(0, 0, currentX + kWidthColumn, kHeightSection);
        
        [sectionView addSubview:view];
    }

    return sectionView;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSString *reuseIdentifier = @"ONRealTimeTableViewCell";
    
    if (self.isShowingSelectColumnView) {
        
        // menu
        if (indexPath.row<[self.columnMenuArray count]) {
            
            reuseIdentifier = @"ONRealTimeMenuTableViewCell";
            
            ONRealTimeMenuTableViewCell *cell = (ONRealTimeMenuTableViewCell*)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
            if (!cell) {
                cell = (ONRealTimeMenuTableViewCell *)[[[NSBundle mainBundle] loadNibNamed:reuseIdentifier owner:self options:nil] objectAtIndex:0];
            }
            
            NSMutableArray *columnItem = [self.columnMenuArray objectAtIndex:indexPath.row];
            
            
            cell.titleLabel.text = [NSString stringWithFormat:@"%@, %@",[columnItem objectAtIndex:0],[columnItem objectAtIndex:1]];
            if (indexPath.row == self.currentMenuIndex) {
                cell.checkImageView.hidden = NO;
            } else {
                cell.checkImageView.hidden = YES;
            }
            
            return cell;
            
        } else {
            ONRealTimeTableViewCell *cell = (ONRealTimeTableViewCell*)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
            if (!cell) {
                cell = (ONRealTimeTableViewCell *)[[[NSBundle mainBundle] loadNibNamed:reuseIdentifier owner:self options:nil] objectAtIndex:0];
            }
            
            ONISOObjects *oNISOObject = [self.dataArray objectAtIndex:indexPath.row - [self.columnMenuArray count]];
            
            [cell loadCellData_RealTime:oNISOObject withDataUpdate:_dataUpdate andCurrentChoiced:self.currentMenuIndex andNumberColumn:kNumberOfColumnOnRealTime andShowArrow:false];
            
            return cell;
        }

    } else {
        
        ONRealTimeTableViewCell *cell = (ONRealTimeTableViewCell*)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
        if (!cell) {
            cell = (ONRealTimeTableViewCell *)[[[NSBundle mainBundle] loadNibNamed:reuseIdentifier owner:self options:nil] objectAtIndex:0];
        }
        
        ONISOObjects *oNISOObject = [self.dataArray objectAtIndex:indexPath.row];
        [cell loadCellData_RealTime:oNISOObject withDataUpdate:_dataUpdate andCurrentChoiced:self.currentMenuIndex andNumberColumn:kNumberOfColumnOnRealTime andShowArrow:false];
        cell.hidden=[self isInVisibleArray:oNISOObject];
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    // Set background color of cell here if you don't want default white
}

#pragma mark - UITableViewDelegate Methods

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    if (self.isShowingSelectColumnView) {
        
        self.currentMenuIndex = indexPath.row;
        if(self.currentMenuIndex>= [self.columnMenuArray count]){
            
            // not yet lgoin
            if (![self userIsLogin]) {
                [self showLoginScreen];
            }
            [tableView deselectRowAtIndexPath:indexPath animated:YES];
            return;
        }
        // update value for column name (update this function later)
        ONColumnTitleObject *column1 = [self.columnArray objectAtIndex:1];
        ONColumnTitleObject *column2 = [self.columnArray objectAtIndex:2];
         ONTabbarViewController *tabbar =(ONTabbarViewController*)self.tabBarController;
        tabbar.ChoiceTypeDataFilter = self.currentMenuIndex;
        NSMutableArray *columnItem = [self.columnMenuArray objectAtIndex:self.currentMenuIndex];
        [APP_DELEGATE savingCurrentColumnNameRealTime:columnItem];
        
        NSString *item =[columnItem objectAtIndex:0];
        NSString *strHigh=@"";
        NSString *strLow=@"";
        if([item isEqualToString:@"Hourly High"])
        {
            strHigh =@"High (H)";
            strLow =@"Low (H)";
        }
        else if([item isEqualToString:@"Daily High"])
        {
            strHigh =@"High (D)";
            strLow =@"Low (D)";
        }
        else if([item isEqualToString:@"Weakly High"])
        {
            strHigh =@"High (W)";
            strLow =@"Low (W)";
        }
        else
        {
            strHigh =@"High (M)";
            strLow =@"Low (M)";
            ///Monthly High
        }
        
        
//        column1.name = [NSString stringWithFormat:@"%@ ▾",[columnItem objectAtIndex:0]];  ///--> don't remove
//        column2.name = [NSString stringWithFormat:@"%@ ▾",[columnItem objectAtIndex:1]];  ///--> don't remove
        column1.name = [NSString stringWithFormat:@"%@",strHigh];
        column2.name = [NSString stringWithFormat:@"%@",strLow];
        
        self.isShowingSelectColumnView = NO;
        [self.tableView reloadData];
    }
    else
    {
        // not yet lgoin
        if (![self userIsLogin]) {
            [self showLoginScreen];
            return;
        }
        
        /// choice columns
         ONISOObjects *selected =[self.dataArray objectAtIndex:indexPath.row];
        if([self checkingHasChildByName:selected.name])
        {
        
            ONRealTimeViewController *vc =(ONRealTimeViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"ONRealTimeViewController"];
        
            //vc.level=_level+1;
            vc.iData=[NSMutableArray arrayWithArray:self.iData];
            ONISOObjects *oNISOObject = [self.dataArray objectAtIndex:indexPath.row];
            if(oNISOObject.type==LEVEL_ISO)
            {
                vc.ISO = oNISOObject.name;
            }
            
            else if(oNISOObject.type==LEVEL_LOADZONE)
            {
                vc.ISO = oNISOObject.iso;
                vc.LOADZONE = oNISOObject.name;
            }
            else
            {
                [tableView deselectRowAtIndexPath:indexPath animated:YES];
                return;
            }
           
             vc.level=oNISOObject.type+1;
            vc.columnArray=[NSMutableArray arrayWithArray:_dynamicColumnBackUp];
            
            
            NSLog(@"ISO %@ - LOADZONE %@ ",vc.ISO,vc.LOADZONE);
            [self.navigationController pushViewController:vc animated:YES];
        }
        
    }
    // Deselect the row
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}




#pragma mark - SWTableViewDelegate

- (void)swipeableTableViewCell:(SWTableViewCell *)cell scrollingToState:(SWCellState)state
{
    switch (state) {
        case 0:
            NSLog(@"utility buttons closed");
            break;
        case 1:
            NSLog(@"left utility buttons open");
            break;
        case 2:
            NSLog(@"right utility buttons open");
            break;
        default:
            break;
    }
}

- (void)swipeableTableViewCell:(SWTableViewCell *)cell didTriggerRightUtilityButtonWithIndex:(NSInteger)index
{
    switch (index) {
        case 0:
            NSLog(@"Right button 0 was pressed");
            break;
            
        case 1: {
            // Delete button was pressed
            NSIndexPath *cellIndexPath = [self.tableView indexPathForCell:cell];
                        
            // remove object in data list
            [self.dataArray removeObjectAtIndex:cellIndexPath.row];
            
            // remove cell
            [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:cellIndexPath] withRowAnimation:UITableViewRowAnimationLeft];
        }
            break;
            
               default:
            break;
    }
}

- (BOOL)swipeableTableViewCellShouldHideUtilityButtonsOnSwipe:(SWTableViewCell *)cell
{
    // allow just one cell's utility button to be open at once
    return YES;
}

- (BOOL)swipeableTableViewCell:(SWTableViewCell *)cell canSwipeToState:(SWCellState)state
{
    switch (state) {
        case 1:
            // set to NO to disable all left utility buttons appearing
            return YES;
            break;
        case 2:
            // set to NO to disable all right utility buttons appearing
            return YES;
            break;
        default:
            break;
    }
    
    return YES;
}

#pragma mark - Request And Call Back  Methods Webservice

// when pull down refresh, this method will be called
- (void)requestGetData {
   
    NSLog(@"REQUEST RELOAD DATA");
    //[self performSelector:@selector(doneLoadingTableViewData) withObject:nil afterDelay:1];
    [[NSNotificationCenter defaultCenter] postNotificationName:UPDATE_REAL_TIME object:self.dataArray userInfo:nil];
}
-(void)updateDataRealtime:(NSMutableArray *)sender
{
    NSLog(@"%s",__FUNCTION__);
    _dataUpdate =[NSMutableArray arrayWithArray:sender];
    [self.tableView reloadData];
    [self doneLoadingTableViewData];
    
}
-(void)initDelegateTabbar:(BOOL)value
{
    ONTabbarViewController *_tabbar =(ONTabbarViewController*)self.tabBarController;
    if(value){
        _tabbar.tabbarDelegateRealTime=self;
    }
    else
    {
        _tabbar.tabbarDelegateRealTime=nil;
    }
}
-(void)requestUpdateData
{
    if(_postNotifiGetData==true)
    {
        [[NSNotificationCenter defaultCenter] postNotificationName:UPDATE_REAL_TIME object:self.dataArray userInfo:nil];
    }
}
-(void)updateColumnName:(NSMutableArray *)sender
{
    NSLog(@"Number Column %ld",(long)[sender count]);
    
    NSMutableArray * tempRemove= [[NSMutableArray alloc] init];
    for (int index = 0; index < [self.columnArray count]; index++) {
        ONColumnTitleObject *column =[self.columnArray objectAtIndex:index];
        if(column.mainColumn==1)
        {
            [tempRemove addObject:column];
        }
    }
    
    self.columnArray = [NSMutableArray arrayWithArray:tempRemove];
    ///------------ UPDATE COLUMN DYNAMIC ----------//
    int iDynamicColumn =(int)[sender count];
    
    _dynamicColumnBackUp =[[NSMutableArray alloc] init];
    for (int index=0; index<iDynamicColumn; index++)
    {
        ONObjectColumn  *item =[sender objectAtIndex:index];
        ONColumnTitleObject *column = [[ONColumnTitleObject alloc]init];
        column.name = [NSString stringWithFormat:@"%@",item.nameColumn];
        column.allowToSelect = NO;
        column.mainColumn=0;
        [self.columnArray addObject:column];
        [_dynamicColumnBackUp addObject:column];
        
    }
    // Saving Dynamic Column Name
    [APP_DELEGATE savingListDynamicColumnName:_dynamicColumnBackUp andRealTime:YES];
    
    
    
    kNumberOfColumnOnRealTime =3+iDynamicColumn;
    /// update UI
    [self updateUIForViewWithColumn:kNumberOfColumnOnRealTime];
    [self.tableView reloadData];
}
#pragma mark - CLICK DONE DELEGATE
-(void)clickDone
{
    
    NSLog(@"%s",__FUNCTION__);
    _iData =[NSMutableArray arrayWithArray:self.dataArray];
    // NSLog(@"%s",__FUNCTION__);
    [self customizeDataSaving:true];
    [self requestGetData];
    
}

-(void)dealloc
{
   [self initDelegateTabbar:false];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:SAVING_DATA_REAL_TIME object:nil];
}

@end
